var db = require('../db/dbmgr').getDB(),
    async = require('async'),
    logger = require('../libs/logger').logger,
    helper = require('../libs/helper');

var Note = function (obj) {
    this.ID = obj.ID || null;
    this.Title = obj.Title || null;
    this.Narrative = obj.Narrative || null;
};

Note.prototype = {
    validate: function () {
        if (helper.isEmpty(this.Title)) {
            return new Error('标题不能为空');
        }
        return null;
    },
    save: function (next) {
        var err = this.validate();
        if (err) return next(err);

        if (this.ID) { //修改
            this.update(next);
        } else { //新增
            var me = this;
            db.run('insert into Notes (Title, Narrative, CreateTime) values (?, ?, ?)', [me.Title, me.Narrative, new Date().getTime()], function (err) {
                if (err) {
                    logger.error(err);
                    return next(err);
                } else {
                    if (!this.lastID) {
                        err = new Error('没有插入任何行');
                        logger.debug(err);
                        return next(err);
                    }
                    me.ID = this.lastID;
                }
                next(err, me);
            });
        }
    },
    update: function (next) {
        var me = this;

        db.run('update Notes set Title = ?, Narrative = ?, UpdateTime = ? where ID = ?', [me.Title, me.Narrative, new Date().getTime(), me.ID], function (err) {
            if (err) {
                logger.error(err);
                return next(err);
            } else {
                if (this.changes == 0) {
                    err = new Error('没有更新任何行');
                    logger.debug(err);
                    return next(err);
                }
            }
            next(err, me);
        });
    },

    delete: function (next) {
        var me = this;

        Note.delete(me.id, next);
    },

    toJSON: function () {
        var tmp = {};

        for (var key in this) {
            if (typeof this[key] !== 'function')
                tmp[key] = this[key];
        }

        return tmp;
    }
};

Note.delete = function (id, next) {
    if (helper.isEmpty(id)) {
        return next(new Error('id不能为空'));
    }
    db.run('delete from Notes where ID = ?', [id], function (err) {
        if (err) {
            logger.error(err);
        } else {
            if (this.changes == 0) {
                err = new Error('没有删除任何行');
                logger.debug(err);
                return next(err);
            }
        }
        next(err);
    });
};

Note.get = function (id, next) {
    db.get('select * from Notes where ID = ?', [id], function (err, row) {
        if (err) {
            logger.error(err);
        } else {
            if (!row) {
                err = new Error('没有找到任何行');
                logger.debug(err);
                return next(err);
            }
        }
        next(err, row);
    });
};

Note.findAllOfPage = function (storeParams, fields, next) {
    var limit = storeParams.limit,
        offset = storeParams.start,
        sort = storeParams.sort,
        filter = storeParams.filter,

        filterParams = [],
        filterStr = '',
        sortStr = '',
        sortArr = [];
    if (helper.isArray(sort)) {
        sortArr = sort.map((s) => {
            return s.property + ' ' + s.direction;
        });
    }
    if (sortArr.length) {
        sortStr = ' order by ' + sortArr.join(', ');
    }
    if (helper.isArray(filter)) {
        filter.every(function (f) {
            if (f.property == 'search' && !helper.isEmpty(f.value)) {
                filterParams.push('%' + f.value + '%');
                filterStr = " where Title like ? or Narrative like ? ";
                return false; //break
            }
            return true; //continue
        });
    }

    var fieldStr = '';
    if(fields && fields.length) {
        fieldStr = fields.join(', ');
    }
    else {
        fieldStr = '*';
    }

    var getPageData = function (cb) {
        db.all('Select ' + fieldStr + ' From Notes ' + filterStr + sortStr + ' Limit ' + limit + ' offset ' + offset, filterParams, function (err, data) {
            logger.debug('get Notes data of page', err, data);

            cb(err, data);
        });
    };
    var getTotalCnt = function (cb) {
        db.get('Select count(*) Cnt From Notes ' + filterStr, filterParams, function (err, data) {
            logger.debug('get Notes total count', err, data);

            cb(err, data);
        });
    };

    async.parallel([getPageData, getTotalCnt], function (err, results) {
        if (err) {
            logger.error(err);
            return next(err);
        } else {
            var data = results[0],
                total = results[1].Cnt;

            next(null, {
                total: total,
                data: data
            });
        }
    });
};

module.exports = Note;